package com.attack.api.aop;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.attack.api.annotation.ExtApiIdempotent;
import com.attack.api.utils.BaseRedisService;
import com.attack.api.utils.ConstantUtils;

@Aspect
@Component
public class ExtApiAopIdempotent {
	@Autowired
	private BaseRedisService baseRedisService;
	// 1.使用AOP环绕通知拦截所有访问（controller）
	@Pointcut("execution(public * com.attack.controller.*.*(..))")
	public void rlAop() {
	}
	// 环绕通知
	@Around("rlAop()")
	public Object doBefore(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		//获取请求的方法
		Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod();
	    //判断请求的方法上是否有ExtApiIdempotent注解
	    ExtApiIdempotent extApiIdempotent= method.getDeclaredAnnotation(ExtApiIdempotent.class);
	    if(extApiIdempotent==null){
	    	return proceedingJoinPoint.proceed();//放行
	    }
	    String type=extApiIdempotent.type();
	    String token=null;
	    if(ConstantUtils.EXTAPIHEAD.equals(type)){
	    	//从请求头中获取token
	    	token=getRequest().getHeader("token");
	    }else{
	    	//从表单中获取的token
	    	token=getRequest().getParameter("token");
	    }
	    if(StringUtils.isEmpty(token)){
	    	response("token不能为空！！！！");
	    	return null;
	    }
	    String redisResult=(String) baseRedisService.getString(token);
	    if(StringUtils.isEmpty(redisResult)){
	    	response("token无效！！！！");
	    	return null;
	    }
	    baseRedisService.delKey(token);
		return proceedingJoinPoint.proceed();//放行
	}
	/**
	 * 获取request
	 * @return
	 */
	public HttpServletRequest getRequest() {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		return request;
	}
	/**
	 * 获取response
	 * @param msg
	 * @throws IOException
	 */
	public void response(String msg) throws IOException {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletResponse response = attributes.getResponse();
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		PrintWriter writer = response.getWriter();
		try {
			writer.println(msg);
		} catch (Exception e) {

		} finally {
			writer.close();
		}

	}
}
